﻿using System;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media.Effects;
using Caliburn.Micro;

namespace Scrabble.Tasks
{
    public class DisplayPopup<TScreen> : IResult where TScreen : IScreen
    {
        public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };
        
        public DisplayPopup(TScreen screen)
        {
            Screen = screen;
        }

        public TScreen Screen { get; private set; }

        public void Execute(ActionExecutionContext context)
        {
            var content = new ContentControl();
            View.SetModel(content, Screen);

            var popup = new Popup
                        {
                            Child = content,
                            AllowsTransparency = true,
                            Effect = new DropShadowEffect { Opacity = 0.3 }
                        };

            popup.SetValue(View.IsGeneratedProperty, true);
            popup.Closed += delegate { Screen.Deactivate(true); };

            if (context.Source != null)
            {
                MouseEventHandler handler = delegate { popup.StaysOpen = false; };
                context.Source.MouseLeave += handler;

                popup.PlacementTarget = context.Source;
                popup.Width = context.Source.ActualWidth;
                popup.Closed += delegate { context.Source.MouseLeave -= handler; };
            }

            ViewModelBinder.Bind(Screen, popup, null);

            popup.IsOpen = true;
            popup.Focus();
            popup.CaptureMouse();

            Screen.Activate();

            Completed(this, new ResultCompletionEventArgs());
        }
    }
}